﻿Imports System.ComponentModel
Imports System.Net.NetworkInformation
Imports HslCommunication.LogNet
Imports HslCommunication.Profinet.Siemens
Public Class frmPQ
    Private g_szInitFileName As String
    Private logfile As ILogNet
    Private plc As SiemensS7Net
    Private objDB As New clsEquit_HB_PQ
    Private Power_Inserted As Boolean

    Public Sub New()
        AddHandler AppDomain.CurrentDomain.AssemblyResolve, New ResolveEventHandler(AddressOf CurrentDomain_AssemblyResolve)
        ' 此调用是设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。

    End Sub

    Private Function CurrentDomain_AssemblyResolve(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
        Dim dllName As String = If(args.Name.Contains(","), args.Name.Substring(0, args.Name.IndexOf(","c)), args.Name.Replace(".dll", ""))
        dllName = dllName.Replace(".", "_")
        If dllName.EndsWith("_resources") Then
            Return Nothing
        End If
        Dim rm As New System.Resources.ResourceManager([GetType].Namespace & ".Resources", System.Reflection.Assembly.GetExecutingAssembly())
        Dim bytes As Byte() = DirectCast(rm.GetObject(dllName), Byte())
        Return System.Reflection.Assembly.Load(bytes)
    End Function
    Private Sub frmPQ_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not HslCommunication.Authorization.SetAuthorizationCode("e3e27344-1a9f-4d8b-b4fc-da5cae4b99bf") Then

        End If

        Me.g_szInitFileName = My.Application.Info.DirectoryPath & "\PQ.ini"
        logfile = New LogNetDateTime(Application.StartupPath & "\\Logs", GenerateMode.ByEveryDay)
        connectDB()

        '读PLC
        Dim plcIP As String = GetIniFile("IP", "PLC", "", Me.g_szInitFileName)
        plc = New SiemensS7Net(SiemensPLCS.S200Smart)
        With plc
            .IpAddress = plcIP
            .Port = 102
            .SetPersistentConnection()
        End With

        readPLC()
        Timer1.Interval = 3 * 60 * 1000
        Timer1.Start()
    End Sub

    Private Sub readPLC()

        Dim _en As New en_equit_hb_PQ_item
        dgvErr.DataSource = Nothing
        dgvErr.Refresh()

        'Dim dt As DataTable = objDB.selectErrorAll()
        'If dt.Rows.Count = 0 Then
        '    Exit Sub
        'Else
        '    dgv.DataSource = dt
        'End If

        'Dim plcIP As String = GetIniFile("IP", "PLC", "", Me.g_szInitFileName)
        'Dim ping = New Net.NetworkInformation.Ping()
        'Dim pingResult1F As Net.NetworkInformation.PingReply = ping.Send(plcIP)
        'Try
        '    If pingResult1F.Status <> Net.NetworkInformation.IPStatus.Success Then
        '        With _en
        '            .save_time = Now                                   ' 保存时间
        '            .power_on = False           ' 开关机状态
        '            If .power_on = False And Power_Inserted = True Then
        '                Dim dt As DataTable = objDB.selectErrorAll()
        '                If dt.Rows.Count = 0 Then
        '                    Exit Sub
        '                Else
        '                    dgv.DataSource = dt
        '                End If

        '                Exit Sub
        '            ElseIf .power_on = False And Power_Inserted = False Then
        '                Power_Inserted = True
        '            End If

        '            If .power_on = False Then
        '                objDB.insert(_en)
        '                Dim dt As DataTable = objDB.selectErrorAll()
        '                If dt.Rows.Count = 0 Then
        '                    Exit Sub
        '                Else
        '                    dgv.DataSource = dt
        '                End If
        '                Exit Sub
        '            End If
        '        End With
        '    End If
        'Catch ex As Exception

        'End Try

        Dim dtData As DataTable = objDB.selectData()
        dgvData.DataSource = dtData

        Dim dt As DataTable = objDB.selectErrorAll()
        If dt.Rows.Count > 0 Then
            dt.Columns.Add("value")
        End If

        Try
            With _en
                'Q0.7	BOOL	主排风机 运行中继
                'Q1.1	BOOL	脱附风机 运行中继
                If plc.ReadBool("Q0.7").IsSuccess Or plc.ReadBool("Q1.1").IsSuccess Then
                    .power_on = plc.ReadBool("Q0.7").Content Or plc.ReadBool("Q1.1").Content ' 开关机状态
                Else
                    .power_on = False
                End If
                If .power_on = True Then ' 开关机状态
                    For Each _dr As DataRow In dt.Rows

                        Dim err As Boolean = plc.ReadBool(_dr("plc_address")).Content
                        _dr("value") = err
                        If err Then
                            objDB.insertError(_dr("note"))
                        End If
                    Next
                End If

                dgvErr.DataSource = dt
                '保存数据库

                .save_time = Now   ' 保存时间

                If .power_on = False And Power_Inserted = True Then
                    Exit Sub
                ElseIf .power_on = False And Power_Inserted = False Then
                    Power_Inserted = True
                End If
                If .power_on = False Then
                    objDB.insert(_en)
                    Exit Sub
                End If
                If plc.ReadBool("I0.2").Content Then
                    .run_modle = 0                             ' 运行模式:1为手动，0为自动
                ElseIf plc.ReadBool("I0.3").Content Then
                    .run_modle = 1                             ' 运行模式:1为自动，0为手动
                End If

                If plc.ReadBool("Q2.3").Content Then
                    'Q2.3	BOOL	F01 碳箱A 吸附进气阀 运行中继
                    'Q2.4	BOOL	F02 碳箱A 吸附出气阀 运行中继
                    .box_a = 1         ' 箱体状态:1为吸附，2为脱附
                ElseIf plc.ReadBool("Q2.5").Content Then
                    'Q2.5	BOOL	F03 碳箱A 脱附进气阀 运行中继
                    'Q2.6	BOOL	F04 碳箱A 脱附出气阀 运行中继
                    .box_a = 2         ' 箱体状态:1为吸附，2为脱附
                End If

                If plc.ReadBool("Q2.7").Content Then
                    'Q2.7	BOOL	F05 碳箱B 吸附进气阀 运行中继
                    'Q8.0	BOOL	F06 碳箱B 吸附出气阀 运行中继
                    .box_b = 1          ' 箱体状态:1为吸附，2为脱附
                ElseIf plc.ReadBool("Q8.1").Content Then
                    'Q8.1	BOOL	F07 碳箱B 脱附进气阀 运行中继
                    'Q8.2	BOOL	F08 碳箱B 脱附出气阀 运行中继
                    .box_b = 2          ' 箱体状态:1为吸附，2为脱附
                End If
                If plc.ReadBool("Q8.3").Content Then
                    'Q8.3	BOOL	F09 碳箱C 吸附进气阀 运行中继
                    'Q8.4	BOOL	F10 碳箱C 吸附出气阀 运行中继
                    .box_c = 1     ' 箱体状态:1为吸附，2为脱附
                ElseIf plc.ReadBool("Q8.5").Content Then
                    'Q8.5	BOOL	F11 碳箱C 脱附进气阀 运行中继
                    'Q8.6	BOOL	F12 碳箱C 脱附出气阀 运行中继
                    .box_c = 2     ' 箱体状态:1为吸附，2为脱附
                End If
                'I129.5	BOOL	主排风机 风压开关检测 信号
                'I129.6	BOOL	脱附风机 风压开关检测 信号
                'Q0.7	BOOL	主排风机 运行中继
                'Q1.1	BOOL	脱附风机 运行中继
                If plc.ReadBool("I129.5").Content And plc.ReadBool("Q0.7").Content Then
                    .xf_fj = True     ' 吸附风机状态
                Else
                    .xf_fj = False     ' 吸附风机状态
                End If
                If plc.ReadBool("I129.6").Content And plc.ReadBool("Q1.1").Content Then
                    .tf_fj = True 'plc.ReadBool("I129.6").Content    ' 脱附风机状态
                Else
                    .tf_fj = False 'plc.ReadBool("I129.6").Content    ' 脱附风机状态
                End If
                .temp_tf = plc.ReadFloat("VD3020").Content ' 脱附温度
                ' 箱体温度T7-T12
                .temp_box_t7 = plc.ReadFloat("VD3024").Content
                .temp_box_t8 = plc.ReadFloat("VD3028").Content
                .temp_box_t9 = plc.ReadFloat("VD3032").Content
                .temp_box_t10 = plc.ReadFloat("VD3036").Content
                .temp_box_t11 = plc.ReadFloat("VD3040").Content
                .temp_box_t12 = plc.ReadFloat("VD3044").Content

                .temp_jr = plc.ReadFloat("VD3004").Content ' 加热温度
                .temp_rs = plc.ReadFloat("VD3008").Content  ' 燃烧温度

                .po3_pa = plc.ReadFloat("VD3060").Content
                .po4_pa = plc.ReadFloat("VD3064").Content
                .po5_pa = plc.ReadFloat("VD3068").Content

                'V120.0 BOOL 故障指示触发 P03 过滤箱1#过滤压差 预警
                'V120.1 BOOL 故障指示触发 P04 过滤箱2#过滤压差 预警
                'V120.2 BOOL 故障指示触发 P05 过滤箱3#过滤压差 预警
                'V121.0 BOOL 故障指示触发 P03 过滤箱1#过滤压差 停机
                'V121.1 BOOL 故障指示触发 P04 过滤箱2#过滤压差 停机
                'V121.2 BOOL 故障指示触发 P05 过滤箱3#过滤压差 停机
                '以上任何一个为true就为故障 过滤器状态:0为正常，1为故障
                If plc.ReadBool("V120.0").Content = False And
                  plc.ReadBool("V120.1").Content = False And
                  plc.ReadBool("V120.2").Content = False And
                  plc.ReadBool("V121.0").Content = False And
                  plc.ReadBool("V121.1").Content = False And
                  plc.ReadBool("V121.2").Content = False Then
                    .filter_status = 0
                Else
                    .filter_status = 1
                End If

            End With
            Power_Inserted = False
            objDB.insert(_en)

        Catch ex As Exception

            logfile.WriteError("Connect Failed:" & ex.Message)
        End Try

    End Sub

    Public Sub connectDB()
        'イニシャルファイル情報取得

        g_Server.szDrive = GetIniFile("SERVER", "DRIVE", "PostgreSQL ANSI", g_szInitFileName)
        g_Server.szIPadr = GetIniFile("SERVER", "IP", "", g_szInitFileName)
        g_Server.szDbn = GetIniFile("SERVER", "DBN", "ZHENANSF", g_szInitFileName)
        g_Server.szUid = GetIniFile("SERVER", "UID", "sa", g_szInitFileName)
        g_Server.szPas = GetIniFile("SERVER", "PAS", "sa", g_szInitFileName)
        g_Server.iOver = CInt(GetIniFile("SERVER", "OVER", "-1", g_szInitFileName))

        '得到当前用户名
        g_LoginUser = GetIniFile("LOGIN", "user", "admin", g_szInitFileName)

        If False = g_fDBconnect And 0 = g_iDBconnResult Then
            If "" = g_Server.szIPadr Or "0.0.0.0" = g_Server.szIPadr Then
            Else
                g_fDBconnect = True

                'データベース接続
                With g_Server
                    g_iDBconnResult = DBacs.Connect(.szDrive, .szIPadr, .szDbn, .szUid, .szPas, .iOver)
                    If 1 <> g_iDBconnResult Then
                        .szDrive = CStr(IIf("PostgreSQL" = .szDrive, "PostgreSQL ANSI", "PostgreSQL"))
                        g_iDBconnResult = DBacs.Connect(.szDrive, .szIPadr, .szDbn, .szUid, .szPas, .iOver)
                    End If
                End With
            End If
        End If

        setAllErrMsg()
    End Sub

    Private Sub 提取ToolStripMenuItem_Click(sender As Object, e As EventArgs)
        readPLC()
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        readPLC()
    End Sub



    Private Sub 关闭ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 关闭ToolStripMenuItem.Click
        If MsgBox("如关闭系统，则停止喷漆设备监控！" & vbCrLf & "确定要关闭吗？", 4, Me.Text) = MsgBoxResult.Yes Then
            RemoveHandler Me.Closing, AddressOf frmPQ_Closing
            NotifyIcon1.Dispose()
            Timer1.Stop()
            Close()
        End If
    End Sub

    Private Sub frmPQ_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
        Me.Hide()
        e.Cancel = True
    End Sub

    Private Sub NotifyIcon1_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick
        Me.Show()
    End Sub
End Class
Public Class clsEquit_HB_PQ
    Public Function selectErrorAll() As DataTable
        Dim szSql As String = ""
        Dim rtn As DataTable

        szSql &= "SELECT * FROM sf.b_equip_info_hb_pq_error_address "
        rtn = DBacs.ExecuteSql(szSql, -1)
        If IsNothing(rtn) Then
            selectErrorAll = New DataTable
        Else
            selectErrorAll = rtn
        End If
        Return rtn
    End Function
    Public Function insertError(errorInfo As String) As Integer
        Dim szSql As String = String.Empty
        Dim rtn As Integer

        Try
            szSql = "INSERT INTO sf.b_equip_info_hb_pq_error(save_time , error) VALUES (?,?)"
            rtn = DBacs.ExecuteUpdateSql(szSql, -1, Now, errorInfo)

        Catch ex As Exception
            rtn = -2
        End Try
        Return rtn
    End Function

    Public Function selectData() As DataTable
        Dim szSql As String = ""
        Dim rtn As DataTable

        szSql &= "SELECT * FROM sf.b_equip_info_hb_pq order by save_time DESC "
        rtn = DBacs.ExecuteSql(szSql, -1)
        If IsNothing(rtn) Then
            selectData = New DataTable
        Else
            selectData = rtn
        End If
        Return rtn
    End Function
    Public Function insert(_en As en_equit_hb_PQ_item) As Integer
        Dim szSql As String = String.Empty
        Dim rtn As Integer

        Try
            szSql &= "INSERT INTO sf.b_equip_info_hb_pq( save_time , power_on , run_modle , "
            szSql &= "box_a , box_b , box_c , xf_fj , tf_fj , temp_tf , temp_box_t7 , temp_box_t8 ,"
            szSql &= "temp_box_t9 , temp_box_t10 , temp_box_t11 , temp_box_t12 , temp_jr , temp_rs , filter_status, po3_pa, po4_pa,po5_pa ) "
            szSql &= "VALUES ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? ,? ,? , ?)"

            With _en
                rtn = DBacs.ExecuteUpdateSql(szSql, -1, .save_time, .power_on, .run_modle,
                .box_a, .box_b, .box_c, .xf_fj, .tf_fj, .temp_tf, .temp_box_t7, .temp_box_t8,
                .temp_box_t9, .temp_box_t10, .temp_box_t11, .temp_box_t12, .temp_jr, .temp_rs, .filter_status, .po3_pa, .po4_pa, .po5_pa)
            End With
        Catch ex As Exception
            rtn = -2
        End Try
        Return rtn
    End Function
End Class
Public Class en_equit_hb_PQ_item
    Public save_time As DateTime
    Public power_on As Boolean
    Public run_modle As Integer
    Public box_a As Integer
    Public box_b As Integer
    Public box_c As Integer
    Public xf_fj As Boolean
    Public tf_fj As Boolean
    Public temp_tf As Double
    Public temp_box_t7 As Double
    Public temp_box_t8 As Double
    Public temp_box_t9 As Double
    Public temp_box_t10 As Double
    Public temp_box_t11 As Double
    Public temp_box_t12 As Double
    Public temp_jr As Double
    Public temp_rs As Double
    Public po3_pa As Double
    Public po4_pa As Double
    Public po5_pa As Double
    Public filter_status As Integer
End Class
